package com.bbs.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bbs.common.dto.LoginDTO;
import com.bbs.common.entity.SysUser;
import com.bbs.common.exception.CommonException;
import com.bbs.common.mapper.SysUserMapper;
import com.bbs.common.service.VerificationCodeService;
import com.bbs.common.utils.TokenUtils;
import com.bbs.common.vo.LoginVo;
import com.bbs.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * LoginService
 *
 * @author yangjiajia
 * @createdAt 2024/4/2 11:49
 */
@Service
public class LoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private VerificationCodeService verificationCodeService;

    public LoginVo<UserVo> login(LoginDTO loginDTO) {

        if (!verificationCodeService.checkCode(loginDTO.getCodeId(), loginDTO.getCode())) {
            throw new CommonException("验证码不正确");
        }

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getAccount, loginDTO.getAccount());
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if (null == user) {
            throw new CommonException("账号不存在");
        }
        if (!user.getPassword().equals(loginDTO.getPassword())) {
            throw new CommonException("密码不正确");
        }
        if (user.getLockFlag() == 1) {
            throw new CommonException("账号已被锁定，请联系管理员");
        }

        LoginVo<UserVo> loginVo = new LoginVo();
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        loginVo.setUser(userVo);
        String token = TokenUtils.createJWT(BeanUtil.beanToMap(userVo));
        loginVo.setToken(token);

        return loginVo;
    }
}
